package com.rainng.coursesystem.service.leader;

import com.rainng.coursesystem.manager.OptionManager;
import com.rainng.coursesystem.manager.leader.BudgetManager;
import com.rainng.coursesystem.model.entity.MemberEventEntity;
import com.rainng.coursesystem.model.vo.LeaderBudgetVO;
import com.rainng.coursesystem.model.vo.response.ResultVO;
import com.rainng.coursesystem.service.BaseService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

@Service
public class BudgetService extends BaseService {
    private final BudgetManager manager;
    private final OptionManager optionManager;

    public BudgetService(BudgetManager manager, OptionManager optionManager) {
        this.manager = manager;
        this.optionManager = optionManager;
    }

    public ResultVO getPageCount(String eventName, String memberName) {
        Integer leaderId = getUserId();
        return result(manager.getLeaderBudgetPageCount(leaderId, eventName, memberName));
    }

    public ResultVO getPage(Integer index, String eventName, String memberName) {
        Integer leaderId = getUserId();
        return result(manager.getLeaderBudgetPage(index, leaderId, eventName, memberName));
    }

    public ResultVO update(LeaderBudgetVO vo) {
        if (!optionManager.getAllowLeaderBudget()) {
            return failedResult("现在不是定团队最大容量时间!");
        }

        Integer leaderId = getUserId();
        MemberEventEntity memberEvent = manager.getMemberEventById(vo.getMemberEventId());
        if (memberEvent == null) {
            return failedResult("团员选项目Id:" + vo.getMemberEventId() + "不存在");
        }
        if (!manager.getEventById(memberEvent.getEventId()).getLeaderId().equals(leaderId)) {
            return failedResult("此项目非您带领");
        }

        BeanUtils.copyProperties(vo, memberEvent);

        manager.updateMemberEvent(memberEvent);
        return result("定量成功");
    }

    public ResultVO get(Integer memberEventId) {
        if (!optionManager.getAllowLeaderBudget()) {
            return failedResult("现在不是定团最大容量时间!");
        }

        Integer leaderId = getUserId();
        MemberEventEntity memberEvent = manager.getMemberEventById(memberEventId);
        if (memberEvent == null) {
            return failedResult("团员选项目Id:" + memberEventId + "不存在");
        }
        if (!manager.getEventById(memberEvent.getEventId()).getLeaderId().equals(leaderId)) {
            return failedResult("此项目非您带领");
        }

        LeaderBudgetVO vo = new LeaderBudgetVO();
        BeanUtils.copyProperties(memberEvent, vo);
        vo.setMemberEventId(memberEventId);

        return result(vo);
    }
}
